const ora = require("ora"); //加载提示
const figlet = require("figlet"); //打印图行字体的
const chalk = require("chalk"); //打印字体用的
const {promisify} = require("util");
const ncp = promisify(require("ncp")); //拷贝功能
const path = require("path");
const fs = require("fs");
const Inquirer = require("inquirer"); //命令交互

/**
 * 打印错误信息
 * @param {错误信息} mesage 
 */
const errorStr = (message)=>{ //让字体变成红色的显示在打印区
    // console.log(`\x1b[31m${message}\x1b[0m`); //这个也是可以的
    console.log(`错误信息：${chalk.red.underline.bold(message)}`)
    process.exit(1); //直接结束，不让代码继续执行
}
/**
 * 加载函数
 * @param {函数} fn 
 * @param {提示信息} message 
 * @param {参数，数组} data 
 * @returns 返回成功的结果
 */
const loadingFn = (fn,message) => {
    return async (...args)=>{
        const spinner = ora(message);
        spinner.start(); //开始加载
        try{
            const arr = await fn(...args);
            spinner.succeed(); //结束加载
            return arr;
        }catch(err){
            spinner.succeed(); //结束加载
            if(err.response && err.response.data){
                errorStr("\n"+err.response.data)
            }else{
                errorStr("\n"+err.message)
            }
        }
    }
}
/**
 * 检查文件是否存在看是否需要删除
 * @param {文件地址} url 
 * @param {是否强制覆盖} force 
 */
const checkFile = async (url,force = false)=>{
    if(fs.existsSync(url)){
        if(force){
            deleteFolderRecursive(url);
        }else{
            const { isOverWrite } = await Inquirer.prompt({
                name:'isOverWrite',
                type:'list',
                message:'是否覆盖已存在文件',
                choices:[{
                    name:'确定',
                    value:true
                },
                {
                    name:'取消',
                    value:false
                },]
            })
            if(isOverWrite){
                await loadingFn(deleteFolderRecursive,"await delete file ...")(url);
            }else{
                errorStr("取消创建文件")
            }
        }
    }
}
/**
 * 删除文件夹（只有先删除了其下的文件才能删除文件夹）
 * @param {文件路径} path 
 */
const deleteFolderRecursive = (path)=>{
    if( fs.existsSync(path) ) {
        //循环删除目录下的文件
        fs.readdirSync(path).forEach(function(file) {
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}
/**
 * 将目标文件复制到当前工作路径
 * @param {目标地址} target 
 * @param {文件名} projectName 
 */
const copyFile = async (target,projectName)=>{
    await ncp(target,path.resolve(projectName))
}
/**
 * 打印图形字体
 * @param {显示文字} text 
 * @param {参数} option 
 */
const figletFn = (text,option={})=>{
    console.log(
        "\n"+
        figlet.textSync(text||'cyj',{
            font:option.font||"Ghost",
            horizontalLayout:"default",
            verticalLayout:'default',
            width:option.width||80,
            whitespaceBreak:true
        })
    )
}
// 下载的临时存放位置，由于mac和window上的地址不一样所以需要判断
const downloadDirectory = `${process.env[process.platform === 'darwin'?'HOME':'USERPROFILE']}/.template`;
module.exports= {
    loadingFn,
    errorStr,
    figletFn,
    downloadDirectory,
    copyFile,
    checkFile,
    deleteFolderRecursive,
}